import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'model/device_model.dart';
import 'package:fcharts/fcharts.dart';

int decimal = 3;

class IncomeRecordPage extends StatefulWidget {
  IncomeRecordPage(this.device,this.mainColor);
  final DeviceModel device;
  final Color mainColor;
  @override
  _IncomeRecordPageState createState() => new _IncomeRecordPageState(device);
}

class Income {
  const Income(this.date, this.income);
  final int date;
  final double income;
}

class _IncomeRecordPageState extends State<IncomeRecordPage> {
  List<Income> incomeArr = [];
  Map get statistic {
    var total = 0.0;
    var max = 0.0;
    var min = 10.0;
    for (var i = 0; i < incomeArr.length; i++) {
      total += incomeArr[i].income;
      max = incomeArr[i].income > max ? incomeArr[i].income : max;
      min = incomeArr[i].income < min ? incomeArr[i].income : min;
    }
    var avg=0.0;
    if(incomeArr.length>0){
      avg = total / incomeArr.length??0.0;
    }

    return {"total": total, "max": max, "min": min, "avg": avg};
  }
  bool has_next = false;
  int has_data = 2;
  bool loading = true;
  DateTime current = new DateTime.now();
  DateTime get prevMonth {
    if (current.month == 1) {
      return new DateTime(current.year - 1, 12);
    } else {
      return new DateTime(current.year, current.month - 1);
    }
  }

  DateTime get nextMonth {
    if (current.month == 12) {
      return new DateTime(current.year + 1, 1);
    } else {
      return new DateTime(current.year, current.month + 1);
    }
  }

  DeviceModel device;
  double maxIncome = 0.1;
  int maxDay = 31;
  _IncomeRecordPageState(this.device) {
    print("xx");
    incomeRecord(current);
  }
  back() {
    Navigator.pop(context);
  }

  incomeRecord(DateTime month) async {
    this.loading = true;
    if (month.month == 12) {
      month = new DateTime(month.year + 1, 1);
    } else {
      month = new DateTime(month.year, month.month + 1);
    }
    this.incomeArr = [];
    var isLogin = await checkLogin(device.sessionid, device.userid);
    print(isLogin);
    bool loginStatus = true;
    if (!isLogin) {
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.device_id, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      } else {
        loginStatus = false;
      }
    }
    if (loginStatus) {
      print("登录有效");

      Map incomeData = await getIncomeRecord(sessionid: device.sessionid, userid: device.userid, year: month.year, month: month.month);
      this.has_data = incomeData['has_data'] ? 1 : 0;
      this.has_next = incomeData['has_next'];
      if (incomeData['has_data'] == false && incomeData['has_next'] == false) {
        setState(() {});
        return;
      }
      for (int i = incomeData['incomeArr'].length; i > 0; i--) {
        var income = incomeData['incomeArr'][i - 1];
        int dateAdd = int.parse(income['date']);
        double incomeAdd = double.parse(income['num']);
        this.incomeArr.add(new Income(dateAdd % 100, incomeAdd));
        if (incomeAdd > maxIncome) {
          maxIncome = incomeAdd;
        }
        maxDay = dateAdd % 100;
      }
      this.loading = false;
      setState(() {});
    } else {
      showDialog<Null>(
        context: context,
        builder: (ctx) {
          return new AlertDialog(
            title: new Text("错误提醒"),
            content: new Text("获取提币记录失败，请重试"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () async {
                  incomeRecord(current);
                },
                child: new Text(
                  '重试',
                ),
              ),
              new FlatButton(
                onPressed: () async {
                  back();
                  back();
                },
                child: new Text(
                  '返回',
                ),
              ),
            ],
          );
        },
      );
    }
  }

  Widget _buildTiles(Income income) {
    return new Column(
      children: <Widget>[
        new ListTile(
          title: new Text(
            income.date.toString() + "日",
            style: new TextStyle(fontSize: 16.0),
          ),
          trailing: new Text(
            income.income.toString(),
            style: new TextStyle(fontSize: 22.0, color: widget.mainColor),
          ),
        ),
        Divider(height: 1.0),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new CupertinoNavigationBar(
        actionsForegroundColor: Colors.white,
        backgroundColor: widget.mainColor,
        middle: new Text(
          (this.device.device_name ?? "") + "${current.month}月收入",
          style: new TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
      body: new Column(
        children: <Widget>[
          this.incomeArr.length>2?new Container(
            height: 200.0,
            decoration: new BoxDecoration(
              border: new Border(
                bottom: new BorderSide(color: Colors.black12, width: 0.5),
              ),
            ),
            padding: EdgeInsets.only(left: 20.0, bottom: 20.0),
            child: new LineChart(
              lines: [
                new Line<Income, int, double>(
                  data: this.incomeArr,
                  xFn: (datum) => datum.date,
                  yFn: (datum) => datum.income,
                  xAxis: new ChartAxis<int>(
                    span: IntSpan(1, maxDay),
                    tickGenerator: IntervalTickGenerator.byN(3),
                  ),
                  yAxis: new ChartAxis(
                    span: DoubleSpan(0.0, double.parse((maxIncome + 0.2).toStringAsFixed(1))),
                    tickGenerator: IntervalTickGenerator.byN(0.5),
                  ),
                  marker:new MarkerOptions(
                    paint: new PaintOptions.fill(color: widget.mainColor),
                    shape: MarkerShapes.circle,
                  ),
                  stroke: new PaintOptions.stroke(color:widget.mainColor),
                ),
              ],
            ),
          ):this.loading?new Container(
            height: 200.0,
            child: new Center(
              child: new CupertinoActivityIndicator(),
            ),
          ):new Container(
            height: 200.0,
            child: new Center(
              child: new Text("记录不足2条，无法显示图表"),
            ),
          ),
          new Container(
            height: 50.0,
            padding: EdgeInsets.only(top: 5.0,bottom: 5.0),
            decoration: new BoxDecoration(
              border: new Border(
                bottom: new BorderSide(color: Colors.black12, width: 0.5),
              ),
            ),
            child: new Row(
              children: <Widget>[
                new Expanded(child: new Column(
                  children: <Widget>[
                    new Text("总计"),
                    new Text(statistic['total'].toStringAsFixed(decimal)),
                  ],
                ),),
                new Expanded(child: new Column(
                  children: <Widget>[
                    new Text("平均"),
                    new Text(statistic['avg'].toStringAsFixed(decimal)),
                  ],
                ),),
                new Expanded(child:  new Column(
                  children: <Widget>[
                    new Text("最高"),
                    new Text(statistic['max'].toStringAsFixed(decimal)),
                  ],
                ),),
                new Expanded(child: new Column(
                  children: <Widget>[
                    new Text("最低"),
                    new Text(this.loading?0.0.toStringAsFixed(decimal):statistic['min'].toStringAsFixed(decimal)),
                  ],
                ),),

              ],
            ),
          ),
          new Expanded(
            child: this.loading
                ? new CupertinoActivityIndicator()
                : new ListView.builder(
              itemCount: incomeArr.length,
              itemBuilder: (context, i) => _buildTiles(incomeArr[incomeArr.length - 1 - i]),
            ),
          ),
          new Container(
            color: widget.mainColor,
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                new CupertinoButton(
                  child: new Text(
                    "${prevMonth.month}月",
                    style: new TextStyle(color: Colors.white, fontSize: 16.0),
                  ),
                  onPressed: () {
                    if (this.has_next == false) {
                      toast("没有更早的记录");
                      return;
                    }
                    incomeRecord(prevMonth);
                    current = prevMonth;
                    setState(() {});
                  },
                  padding: EdgeInsets.only(top: 0.0, bottom: 0.0),
                ),
                new CupertinoButton(
                  child: new Text(
                    "${nextMonth.month}月",
                    style: new TextStyle(color: Colors.white, fontSize: 16.0),
                  ),
                  onPressed: () {
                    if (nextMonth.compareTo(new DateTime.now()) > 0) {
                      toast("还没到${nextMonth.month}月份");
                      return;
                    }
                    incomeRecord(nextMonth);
                    current = nextMonth;
                    setState(() {});
                  },
                  padding: EdgeInsets.only(top: 0.0, bottom: 0.0),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
